import sys
import pymysql
import paramiko
import threading

class SSHTool():
    def get_ssh_from_mysql(self):
        try:
            dbconn = pymysql.connect(
                host='localhost',
                user='root',
                password='123456',
                database='it'
            )
        except Exception as e:
            print("连接数据库失败")
            raise e  
            sys.exit()

        cr = dbconn.cursor()
        query_sql = "SELECT username, ip, password, port FROM hosts"
        result = cr.execute(query_sql)
        hosts = cr.fetchall()
        cr.close()
        dbconn.close()
        return hosts

    # 连接服务器执行命令
    def execCMD(self, ip, username, password, cmd, port=22):
        if not all([ip, username, password, cmd]):
            raise ValueError("缺少必要的连接参数")

        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        try:
            ssh.connect(hostname=ip, port=port, username=username, password=password)
        except Exception as e:
            print(f"连接服务器 {ip} 失败: {e}")
            sys.exit()

        stdin, stdout, stderr = ssh.exec_command(cmd)
        output = stdout.read().decode("utf-8")
        print("服务器【%s】执行【%s】操作的结果: " % (ip, cmd))
        print(output)
        ssh.close()

    
    def GOINGCMD(self):
        CMD = input("请输入要执行的命令：").strip()
        if not CMD:
            print("命令不能为空")
            return
      
        hosts = self.get_ssh_from_mysql()
        for user, ip, password, port in hosts:
            ssh_thread = threading.Thread(target=self.execCMD, args=(ip, user, password, CMD, port))
            ssh_thread.start()


    def host_status(self,ip,username,password,port=22):
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        try:
            ssh.connect(hostname=ip, port=port, username=username, password=password)
        except Exception as e:
            print(f"连接服务器 {ip} 失败: {e}")
            sys.exit()
        all_status = {}
        # 获取服务器状态
        
        stdin, stdout, stderr = ssh.exec_command("uname -a")
        kernel_version = stdout.read().decode("utf-8").rstrip()
        all_status["内核版本: "] = kernel_version











if __name__ == "__main__":
    hosts = SSHTool()
    hosts.GOINGCMD()
    hosts.host_status()
   
    
